package com.zzsy.carosshopprojects.util.sunmireadcard;

import android.os.RemoteException;
import android.util.Log;

import com.sunmi.pay.hardware.aidl.AidlConstants;
import com.sunmi.pay.hardware.aidlv2.readcard.ReadCardOptV2;
import com.sunmi.pay.hardware.aidlv2.system.BasicOptV2;
import com.sunmi.pay.usdk.aidl.readcard.ReadCardOpt;
import com.sunmi.pay.usdk.aidl.security.SecurityOpt;
import com.sunmi.pay.usdk.kernel.SunmiPayKernel;
import com.zzsy.carosshopprojects.base.BaseApplation;
import com.zzsy.carosshopprojects.util.ApkInfoUtil;
import com.zzsy.carosshopprojects.util.StringUtils;
import com.zzsy.carosshopprojects.util.Utils;

/**
 * 商米读卡辅助类
 */
public class SunmiReadCardHelper {

    private static SunmiReadCardHelper helper;
    private sunmi.paylib.SunmiPayKernel mSMPayKernel;
    private ReadCardOptV2 mReadCardOptV2;
    private BasicOptV2 mBasicOptV2;
    private SecurityOpt mSecurityOpt;
    private SunmiPayKernel mSunmiPayKernel;
    private int pikIndex = 14;
    private ReadCardOpt mReadCardOpt;

    private SunmiReadCardHelper() {
    }

    public static SunmiReadCardHelper getInstance() {
        if (helper == null) {
            helper = new SunmiReadCardHelper();
        }
        return helper;
    }

    /**
     * 商米P2连接设备
     */

    public void connectPayService() {
        mSMPayKernel = sunmi.paylib.SunmiPayKernel.getInstance();
        mSMPayKernel.initPaySDK(BaseApplation.instance(), mConnectCallback);
    }

    private sunmi.paylib.SunmiPayKernel.ConnectCallback mConnectCallback = new sunmi.paylib.SunmiPayKernel.ConnectCallback() {

        @Override
        public void onConnectPaySDK() {
            try {
                mReadCardOptV2 = mSMPayKernel.mReadCardOptV2;
                mBasicOptV2 = mSMPayKernel.mBasicOptV2;
                String versionData = ApkInfoUtil.getVersionData();
                if (!StringUtils.isEmpty(versionData)) {
                    if ("P1_4G".equals(versionData)) {
                        conn();
                        if (mSMPayKernel != null) {
                            mSMPayKernel.destroyPaySDK();
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onDisconnectPaySDK() {
            connectPayService();
        }

    };

    /**
     * 连接商米支付功能
     */
    public void conn() {
        mSunmiPayKernel = SunmiPayKernel.getInstance();
        mSunmiPayKernel.connectPayService(mConnCallback, BaseApplation.instance());
    }

    /**
     * 连接状态回调
     */
    public SunmiPayKernel.ConnectCallback mConnCallback = new SunmiPayKernel.ConnectCallback() {
        @Override
        public void onServiceConnected() {
            /**
             * 连接成功的回调
             * */
            try {
                mReadCardOpt = mSunmiPayKernel.mReadCardOpt;
                mSecurityOpt = mSunmiPayKernel.mSecurityOpt;
                //存储KEK,TMK,PIK,MAK,TDK,各种默认的密钥
                initSecretKey();
                Log.e("wl", "链接成功");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected() {
            Log.e("wl", "链接失败");
        }

        @Override
        public void illegal() {
            Log.e("wl", "非法调用");
        }
    };

    public ReadCardOpt getReadCardOpt() {
        return mReadCardOpt;
    }

    public ReadCardOptV2 getReadCardOptV2() {
        return mReadCardOptV2;
    }

    public BasicOptV2 getBasicOptV2() {
        return mBasicOptV2;
    }
////
////    public SecurityOpt getSecurityOpt() {
////        return mSecurityOpt;
////    }

    /**
     * 存储KEK,TMK,PIK,MAK,TDK,各种默认的密钥
     *
     * @throws RemoteException
     */
    public void initSecretKey() throws RemoteException {
        byte[] kekByte = Utils.hexStr2Bytes("11111111111111111111111111111111");
        byte[] tmkByte = Utils.hexStr2Bytes("F40379AB9E0EC533F40379AB9E0EC533");
        byte[] checkValueByte = Utils.hexStr2Bytes("82E13665B4624DF5");

        /**
         * CheckValue的计算过程：
         KEK（明文） TMK（密文） workKey（密文）
         KEK解密TMK(密文)得到TMK（明文）
         用TMK（明文）解密workKey（密文）得到workKey（明文）
         用workKey（明文）加密16个0 取前8位是CheckValue
         */
        //测试时请将主密钥和工作密钥存入以下索引
        try {
            int rec = mSecurityOpt.saveKey(AidlConstants.Security.KEY_TYPE_KEK, kekByte, checkValueByte, 1, AidlConstants.Security.KEY_ALG_TYPE_3DES, 10, false);
            int rec1 = mSecurityOpt.saveKey(AidlConstants.Security.KEY_TYPE_TMK, tmkByte, checkValueByte, 10, AidlConstants.Security.KEY_ALG_TYPE_3DES, 11, true);
            int rec2 = mSecurityOpt.saveKey(AidlConstants.Security.KEY_TYPE_TDK, tmkByte, checkValueByte, 11, AidlConstants.Security.KEY_ALG_TYPE_3DES, 12, true);
            int rec3 = mSecurityOpt.saveKey(AidlConstants.Security.KEY_TYPE_MAK, tmkByte, checkValueByte, 11, AidlConstants.Security.KEY_ALG_TYPE_3DES, 13, true);
            int rec4 = mSecurityOpt.saveKey(AidlConstants.Security.KEY_TYPE_PIK, tmkByte, checkValueByte, 11, AidlConstants.Security.KEY_ALG_TYPE_3DES, pikIndex, true);
//            LogManager.e("secutirysaveKey", rec + ":" + rec1 + ":" + rec2 + ":" + rec3 + ":" + rec4);
        } catch (RemoteException e) {
            e.printStackTrace();
        }

    }


}
